<?php
namespace app\common\utils;

use OSS\OssClient;
use think\facade\Config;
use think\facade\Log;
use OSS\Core\OssException;

/**
 * OSS上传助手类
 * @author zi-m.cn
 *
 */
class OssFlies
{	
    protected $ossClient;

    protected $accessId;
    
    protected $accessKey;
    
    protected $endpoint;
    
    protected $bucket;

    /**
     * @function    构造方法
     * @param null
     * @return object
     */
    public function __construct()
    {
        //获取配置项，并赋值给对象
        $this->accessId = Config::get('oss.KeyId');
        $this->accessKey = Config::get('oss.KeySecret');
        $this->endpoint = Config::get('oss.Endpoint');
        $this->bucket = Config::get('oss.Bucket');
        
        //实例化OSS
        $this->ossClient = new OssClient($this->accessId,$this->accessKey,$this->endpoint,false);
    }
    
    /**
     * 表单提交文件
     * 分类目录
     * 返回ossurl
     * @param $file
     * @param $dir 
     * @return String || bool  
     */
    public function uploadOss($file)
    {
        $info = '';
        try {
            $info = $file->move('./uploads');
        } catch (\Exception $e) {
            Log::record('[文件上传]:'.$e->getMessage(),'error');
            return false;
        }
        
        if($info){
            // 成功上传后 获取上传信息
            $url = $info->getSaveName();
            $path = './uploads/'.$url;
            $object = 'record/uploads/'.$url;
            // 上传到OSS
            try {
                $this->ossClient->uploadFile($this->bucket, $object, $path);
            } catch (OssException $e) {
                Log::record('[文件上传]OSS:'.$e->getMessage(),'error');
                return false;
            }
            //关闭文件对象并删除本地文件
            $info = null;
            unlink($path);
            
        }else{
            Log::record('[文件上传]:'.$file->getError(),'error');
            return false;
        }
        return $url??false;
    }
    
    /**
     * 删除oss文件
     * @param url 
     * @return bool
     */
    public function unlinkOss($url) {
        try {
            $this->ossClient->deleteObject($this->bucket,$url);            
        } catch (OssException $e) {
            Log::record('[文件删除]OSS:'.$e->getMessage(),'error');
            return false;
        }
        
        return true;
    }
    
    /**
     * 上传变量数据
     * @param String $url
     * @param String $data
     * @return bool
     */
    public function stringOss($url,$data) {
        
        try {            
            $this->ossClient->putObject($this->bucket,$url,$data);
        } catch (OssException $e) {
            Log::record('[变量上传]OSS:'.$e->getMessage(),'error');
            return false;
        }
        return true;
    }
}

